using System.Runtime.InteropServices;
using System.Text;

namespace WIT.Global;

/// <summary>
/// ini配置帮助类
/// </summary>
public class INIHelper
{
	/// <summary>
	/// Write
	/// </summary>
	/// <param name="section">节</param>
	/// <param name="key">键</param>
	/// <param name="value">值</param>
	/// <param name="filePath">ini文件完整路径</param>
	/// <returns></returns>
	[DllImport("kernel32")]
	private static extern long WritePrivateProfileString(string section, string key, string value, string filePath);

	/// <summary>
	/// Read
	/// </summary>
	/// <param name="section">节</param>
	/// <param name="key">键</param>
	/// <param name="defaultValue">读取异常时的默认值</param>
	/// <param name="returnValue">读取到的值，如果该key不存在则返回空值</param>
	/// <param name="size">值允许的大小</param>
	/// <param name="filePath">ini文件完整路径</param>
	/// <returns></returns>
	[DllImport("kernel32")]
	private static extern int GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder returnValue, int size, string filePath);

	/// <summary>
	/// 读取键值
	/// </summary>
	/// <param name="section">节</param>
	/// <param name="key">键</param>
	/// <param name="filePath">ini文件完整路径</param>
	/// <returns></returns>
	public static string ReadValue(string section, string key, string filePath)
	{
		int num = 1024;
		StringBuilder stringBuilder = new StringBuilder(num);
		GetPrivateProfileString(section, key, "", stringBuilder, num, filePath);
		return stringBuilder.ToString();
	}

	/// <summary>
	/// 写入键值
	/// </summary>
	/// <param name="section">节</param>
	/// <param name="key">键</param>
	/// <param name="value">值</param>
	/// <param name="filePath">ini文件完整路径</param>
	public static void WriteValue(string section, string key, string value, string filePath)
	{
		WritePrivateProfileString(section, key, value, filePath);
	}

	/// <summary>
	/// 删除键
	/// </summary>
	/// <param name="section">节</param>
	/// <param name="key">键</param>
	/// <param name="filePath">ini文件完整路径</param>
	public static void DeleteKey(string section, string key, string filePath)
	{
		WritePrivateProfileString(section, key, null, filePath);
	}

	/// <summary>
	/// 删除节
	/// </summary>
	/// <param name="section">节名</param>
	/// <param name="filePath">ini文件路径</param>
	public static void DeleteSection(string section, string filePath)
	{
		WritePrivateProfileString(section, null, null, filePath);
	}
}
